package com.ruoyi.foodworks.service.impl;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.foodworks.domain.WorksStatsVO;
import com.ruoyi.foodworks.mapper.WorksMapper;
import com.ruoyi.foodworks.service.WorksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.foodworks.domain.Works;


/**
 * 作品详情Service业务层处理
 * 
 * @author lpt
 * @date 2025-08-12
 */
@Service
public class WorksServiceImpl implements WorksService
{
    @Autowired
    private WorksMapper worksMapper;

    @Override
    public List<WorksStatsVO> selectWorksWithStatsByAuthorId(Integer authorId) {
        return worksMapper.selectWorksWithStatsByAuthorId(authorId);
    }

    // 实现新方法，查询所有作品的统计信息
    @Override
    public List<WorksStatsVO> selectAllWorksWithStats() {
        return worksMapper.selectAllWorksWithStats();
    }


    /**
     * 查询作品详情
     * 
     * @param workId 作品详情主键
     * @return 作品详情
     */
    @Override
    public Works selectWorksByWorkId(Integer workId)
    {
        return worksMapper.selectWorksByWorkId(workId);
    }

    /**
     * 查询作品详情列表
     * 
     * @param works 作品详情
     * @return 作品详情
     */
    @Override
    public List<Works> selectWorksList(Works works)
    {
        return worksMapper.selectWorksList(works);
    }

    /**
     * 新增作品详情
     * 
     * @param works 作品详情
     * @return 结果
     */
    @Override
    public int insertWorks(Works works)
    {
        works.setCreateTime(DateUtils.getNowDate());
        return worksMapper.insertWorks(works);
    }

    /**
     * 修改作品详情
     * 
     * @param works 作品详情
     * @return 结果
     */
    @Override
    public int updateWorks(Works works)
    {
        return worksMapper.updateWorks(works);
    }

    /**
     * 批量删除作品详情
     * 
     * @param workIds 需要删除的作品详情主键
     * @return 结果
     */
    @Override
    public int deleteWorksByWorkIds(Integer[] workIds)
    {
        return worksMapper.deleteWorksByWorkIds(workIds);
    }

    /**
     * 删除作品详情信息
     * 
     * @param workId 作品详情主键
     * @return 结果
     */
    @Override
    public int deleteWorksByWorkId(Integer workId)
    {
        return worksMapper.deleteWorksByWorkId(workId);
    }

    /**
     * 处理用户互动评论积分流水
     * 
     * @param userId 用户ID
     * @return 处理结果
     */
    @Override
    @Transactional
    public Map<String, Object> processInteractionCommentPoint(Long userId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 调试：先查询所有有效的积分规则
            List<Map<String, Object>> allRules = worksMapper.selectAllValidPointRules();
            System.out.println("所有有效的积分规则: " + allRules);
            
            // 1. 查询互动评论积分规则
            Map<String, Object> pointRule = worksMapper.selectInteractionCommentRule();
            System.out.println("查询到的互动评论积分规则: " + pointRule);
            
            if (pointRule == null) {
                result.put("success", false);
                result.put("message", "未找到有效的互动评论积分规则");
                result.put("debug", "所有有效规则: " + allRules);
                return result;
            }
            
            // 修复类型转换问题：BigInteger -> Long
            Long ruleId;
            if (pointRule.get("id") instanceof java.math.BigInteger) {
                ruleId = ((java.math.BigInteger) pointRule.get("id")).longValue();
            } else {
                ruleId = (Long) pointRule.get("id");
            }
            
            // 修复point_change的类型转换问题
            Integer pointChange;
            if (pointRule.get("point_change") instanceof java.math.BigInteger) {
                pointChange = ((java.math.BigInteger) pointRule.get("point_change")).intValue();
            } else {
                pointChange = (Integer) pointRule.get("point_change");
            }
            
            // 2. 查询用户当前积分
            Object totalPointObj = worksMapper.selectUserTotalPoint(userId);
            System.out.println("用户" + userId + "当前积分: " + totalPointObj);
            
            if (totalPointObj == null) {
                result.put("success", false);
                result.put("message", "用户不存在");
                return result;
            }
            
            // 修复用户积分的类型转换问题
            Integer currentTotalPoint;
            if (totalPointObj instanceof java.math.BigInteger) {
                currentTotalPoint = ((java.math.BigInteger) totalPointObj).intValue();
            } else {
                currentTotalPoint = (Integer) totalPointObj;
            }
            
            // 3. 计算新的积分余额
            Integer newBalance = currentTotalPoint + pointChange;
            System.out.println("用户" + userId + "新的积分余额: " + newBalance);
            
            // 4. 插入积分流水记录
            Map<String, Object> flowParams = new HashMap<>();
            flowParams.put("userId", userId);
            flowParams.put("ruleId", ruleId);
            flowParams.put("point", pointChange);
            flowParams.put("balance", newBalance);
            
            int flowResult = worksMapper.insertPointFlow(flowParams);
            
            // 5. 更新用户积分
            Map<String, Object> updateParams = new HashMap<>();
            updateParams.put("userId", userId);
            updateParams.put("newTotalPoint", newBalance);
            
            int updateResult = worksMapper.updateUserTotalPoint(updateParams);
            
            if (flowResult > 0 && updateResult > 0) {
                result.put("success", true);
                result.put("message", "互动评论积分处理成功");
                result.put("oldBalance", currentTotalPoint);
                result.put("newBalance", newBalance);
                result.put("pointChange", pointChange);
            } else {
                result.put("success", false);
                result.put("message", "互动评论积分处理失败");
            }
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "互动评论积分处理异常: " + e.getMessage());
            e.printStackTrace();
        }
        
        return result;
    }
    
    /**
     * 查询所有有效的积分规则（调试用）
     * 
     * @return 积分规则列表
     */
    @Override
    public List<Map<String, Object>> selectAllValidPointRules() {
        return worksMapper.selectAllValidPointRules();
    }
    
    /**
     * 查询互动评论积分规则（调试用）
     * 
     * @return 积分规则
     */
    @Override
    public Map<String, Object> selectInteractionCommentRule() {
        return worksMapper.selectInteractionCommentRule();
    }
}
